<template>
  <div class="page-container">
    <div class="form-header">
      <h1>添加课程分类</h1>
      <p>创建新的课程分类</p>
    </div>
    
    <el-card class="form-card">
      <el-form
        :model="categoryForm"
        :rules="categoryRules"
        ref="categoryFormRef"
        label-width="100px"
        size="large"
      >
        <el-form-item label="分类名称" prop="title">
          <el-input 
            v-model="categoryForm.title" 
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="分类描述" prop="body">
          <el-input
            v-model="categoryForm.body"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <div class="form-actions">
            <el-button size="large" @click="resetForm">重置</el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSubmit"
              :loading="submitting"
            >
              创建分类
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 已有分类列表 -->
    <el-card class="categories-list-card" v-if="categories.length > 0">
      <template #header>
        <div class="card-header">
          <span>现有分类 ({{ categories.length }}个)</span>
        </div>
      </template>
      
      <div class="categories-grid">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="category-item"
        >
          <h4>{{ category.title }}</h4>
          <p>{{ category.body || '暂无描述' }}</p>
          <div class="category-meta">
            <span>分类ID: {{ category.id }}</span>
            <span>创建时间: {{ formatDate(category.addedTime) }}</span>
            <span>创建者: {{ category.authorName || '未知' }}</span>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 说明提示 -->
    <el-card class="info-card">
      <el-alert
        title="分类说明"
        type="info"
        :closable="false"
        show-icon
      >
        <p>• 分类创建后可在"添加课程"页面中选择使用</p>
        <p>• 每个分类可以包含多个课程</p>
        <p>• 首页会显示前4个分类及其课程</p>
        <p>• 当前用户ID: {{ userStore.user?.id || '未登录' }}</p>
      </el-alert>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import * as api from '../services/api'

const router = useRouter()
const userStore = useUserStore()
const categoryFormRef = ref()
const submitting = ref(false)
const categories = ref([])

const categoryForm = reactive({
  title: '',
  body: ''
})

const categoryRules = {
  title: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, message: '分类名称至少2个字符', trigger: 'blur' }
  ],
  body: [
    { required: true, message: '请输入分类描述', trigger: 'blur' }
  ]
}

// 检查用户登录状态
const checkUserLogin = () => {
  if (!userStore.user || !userStore.user.id) {
    ElMessage.error('请先登录')
    router.push('/login')
    return false
  }
  return true
}

const loadCategories = async () => {
  try {
    console.log('开始加载分类数据...')
    const response = await api.getAllCategories()
    categories.value = Array.isArray(response) ? response : []
    console.log('加载的分类数据:', categories.value)
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.warning('获取分类列表失败')
    categories.value = []
  }
}

const handleSubmit = async () => {
  if (!categoryFormRef.value) return
  
  // 检查登录状态
  if (!checkUserLogin()) {
    return
  }
  
  try {
    await categoryFormRef.value.validate()
    submitting.value = true
    
    const submitData = {
      title: categoryForm.title.trim(),
      body: categoryForm.body.trim(),
      userid: userStore.user.id
    }
    
    console.log('用户信息:', userStore.user)
    console.log('提交的分类数据:', submitData)
    
    // 额外验证
    if (!submitData.userid || submitData.userid <= 0) {
      throw new Error('用户ID无效，请重新登录')
    }
    
    if (!submitData.title) {
      throw new Error('分类名称不能为空')
    }
    
    const result = await api.addCategory(submitData)
    console.log('创建分类结果:', result)
    
    // 检查返回结果
    if (result && (result.insertId || result.id)) {
      ElMessage.success('分类创建成功！')
      
      // 重置表单
      resetForm()
      
      // 重新加载分类列表
      await loadCategories()
    } else {
      console.warn('意外的返回结果:', result)
      ElMessage.warning('分类可能已创建，请查看列表确认')
      await loadCategories()
    }
    
  } catch (error) {
    console.error('创建分类失败:', error)
    
    let errorMessage = '创建分类失败'
    
    if (error.response) {
      console.error('错误响应状态:', error.response.status)
      console.error('错误响应数据:', error.response.data)
      
      if (error.response.status === 500) {
        errorMessage = '服务器内部错误，请检查数据格式'
      } else if (error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN')
  } catch (e) {
    return dateStr
  }
}

onMounted(() => {
  console.log('组件挂载，当前用户:', userStore.user)
  if (checkUserLogin()) {
    loadCategories()
  }
})
</script>

<style scoped>
.page-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 10px 0;
}

.form-header p {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

.form-card, .categories-list-card, .info-card {
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-card {
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.category-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
  transition: box-shadow 0.2s;
}

.category-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-item h4 {
  font-size: 16px;
  color: #303133;
  margin: 0 0 10px 0;
}

.category-item p {
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  margin: 0 0 15px 0;
}

.category-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-card {
  padding: 20px;
}

.info-card p {
  margin: 5px 0;
  color: #606266;
}
</style>